<?php
namespace app\controller\admin;

use app\BaseController;
use think\facade\Request;
use app\model\GoodsModel;
use app\model\CategoryModel;
use think\Exception;
use think\Image;
use app\model\tool\ImageModel;

class Goods extends BaseController
{

    public function get_list( Request $request){


        // global $_GPC;
        $_GPC = Request::param(  );
        $filter = [];
        if( isset( $_GPC['name'] ) ){
            $filter['name'] = $_GPC['name'];
        }

        if( isset($_GPC['status']) ){
            $filter['status'] = $_GPC['status'];
        }

        if( isset($_GPC['price']) ){
            $filter['min-price'] = explode('-', $_GPC['price'])[0];
            $filter['max-price'] = explode('-', $_GPC['price'])[1];
        }

        if( isset($_GPC['category_name']) ){
            $filter['category_name'] = $_GPC['category_name'];
        }
        if( isset($_GPC['brand_name']) ){
            $filter['brand_name'] = $_GPC['brand_name'];
        }

        $list = goodsModel::get_list( $filter );

        foreach( $list as &$goods ){

            // $goods['image'] = imageModel::resize2($goods['image'],100,100);

            $width = 100;
            $height = 100;
            try{

                // $img_path = public_path() . '/storage/' . $goods['image'];
                // $img = Image::open( $img_path );
                
                // $img_name_arr = explode('.', $goods['image'] );
                // $new_img_name = $img_name_arr[0] . '_' . $width .'x' . $height . '.' . $img_name_arr[1];
                // $img->thumb($width, $height)->save( public_path() . '/storage/' . $new_img_name );
                // $goods['image'] = Request::instance()->domain() . '/storage/' . $new_img_name;

                $goods['image'] = ImageModel::resize2( $goods['image'] );
            }catch( \Exception $e ){
                // $goods['image'] = $e->getMessage();
                
                $default_img_name = '/storage/icon.jpg';
                $img_path = public_path() . $default_img_name;
                $img = Image::open( $img_path );

                $img_name_arr = explode('.', $default_img_name );
                $new_img_name = $img_name_arr[0] . '_' . $width .'x' . $height . '.' . $img_name_arr[1];
                $img->thumb($width, $height)->save( public_path() . $new_img_name );
                $goods['image'] = Request::instance()->domain() . $new_img_name;
            }
            

        }
        // echo json_encode( $list );
        return json( $list );


    }


    public function info(){

        // global $_W;
        $uniacid = current_uni_account();
        $goods_id = $_GET['goods_id'];

        $res = [
            'status'=>0,
        ];

        $info = GoodsModel::info( $goods_id );


        if( empty($info ) ){

            $res['status'] = 1;
            $res['description'] = '商品不存在';

        }

        $goods_images = goodsModel::get_goods_images( $goods_id );
        $info['goods_images'] = $goods_images;

        $info['description'] = html_entity_decode( $info['description'], ENT_QUOTES, 'UTF-8');
        $info['category'] = [];
        $categories = goodsModel::get_goods_category( $goods_id );
        if( !empty( $categories ) ){

            $filter = [];
            $category_ids = [];
            foreach( $categories as $cat ){
                $category_ids[] = $cat['category_id'];
            }
            $info['category'] = categoryModel::get_path_list( ['category_ids' => $category_ids] );
            $info['category_ids'] = $category_ids;
        }


        $info['pindan'] = goodsModel::get_goods_pindan( $goods_id );

        // $info['cron_goods'] = $this->url_host . '/app/index.php?c=entry&a=wxapp&m=sm_shop&do=api&i=' . $_W['uniacid'] . '&r=cron.goods.addSaleNumber';
        $info['cron_goods'] = Request::instance()->domain() . '/admin.cron/goods/addSaleNumber?&i=' . $uniacid ;

        $res['product'] = $info;



        echo json_encode( $res );

    }

    public function edit(){

        // global $_GPC;
        $_GPC = Request::param();
        $goods_id = $_GPC['goods_id'];
        $res = [
            'status'=>0,
        ];

        $goods_images = [];
        if( !empty( $_GPC['goods_images'] ) ){

            if( is_array($_GPC['goods_images']) ){
                $goods_images = $_GPC['goods_images'];
            }else{
                $_GPC['goods_images'] = htmlspecialchars_decode($_GPC['goods_images']);
                $goods_images = json_decode( $_GPC['goods_images'], true );
            }

        }

        $categories = [];
        if( !empty( $_GPC['category'] ) ){
            $categories = $_GPC['category'];
        }

        $pindan = [];
        if( !empty( $_GPC['pindan'] ) ){
            $pindan = $_GPC['pindan'];
        }

        $data = [
            'name'          => $_GPC['name'],
            'brand_id'      => $_GPC['brand_id']?? 0,
            'price'         => $_GPC['price'],
            'special'       => $_GPC['special']?? 0,
            'sale'          => $_GPC['sale']??0,
            'sale_add'      => $_GPC['sale_add']??0,
            'model'         => $_GPC['model']??'',
//            'description'   => strip_tags( htmlentities( $_GPC['description'] ,ENT_QUOTES, 'UTF-8' )),
            'description'   => $_GPC['description']??'',
            'goods_images'  => $goods_images,
            'image'         => $_GPC['image']??'',
            // 'status'        => $_GPC['status'] ? intval( $_GPC['status'] ) : 1,
            'status'        => $_GPC['status'] ?? 1,
            'category'      => $categories,
            'pindan'        => $pindan,
        ];



        $edit = GoodsModel::edit( $goods_id, $data );

        $res['edit'] = $edit;
        echo json_encode( $res );

    }


    /**
     * 逻辑删除商品（软删除）
     * @return \think\response\Json
     */
    public function remove(){
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '删除成功'
        ];
        
        try {
            $result = GoodsModel::remove( $ids );
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '删除失败：' . $e->getMessage();
        }
        
        return json( $res );
    }
    
    /**
     * 恢复已删除的商品
     * @return \think\response\Json
     */
    public function restore(){
        
        $ids = $_POST['ids'];
        
        $res = [
            'status' => 0,
            'message' => '恢复成功'
        ];
        
        try {
            $result = GoodsModel::restore( $ids );
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '恢复失败：' . $e->getMessage();
        }
        
        return json( $res );
    }
    
    /**
     * 彻底删除商品（物理删除）
     * @return \think\response\Json
     */
    public function forceDelete(){
        
        $ids = $_POST['ids'];
        
        $res = [
            'status' => 0,
            'message' => '彻底删除成功'
        ];
        
        try {
            $result = GoodsModel::forceDelete( $ids );
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '删除失败：' . $e->getMessage();
        }
        
        return json( $res );
    }

    public function search(){

        $filter = [];
        if( !empty( $_GET['filter']) ) {
            $filter['name'] = $_GET['filter'];
        }

        $list = GoodsModel::search( $filter );

        return json( $list );

    }

    public function save_specification(){

        $res['status'] = 0;

        $goods_id = $_GET['goods_id'];

        if( !empty( $_POST['specification'] ) ){
            $specification = json_decode( $_POST['specification'], true);
        }

        if( !empty( $_POST['spec_obj'] ) ){
            $spec_obj = json_decode( $_POST['spec_obj'], true );
        }

//        print_r( $spec_obj );

        goodsModel::delete_spec( $goods_id );

        foreach( $specification as $spec ){
            goodsModel::save_spec( $goods_id, $spec );
        }

        $res['ret'] = goodsModel::save_spec_obj( $goods_id, $spec_obj );

        echo json_encode( $res );

    }

    public function specification(){

        $goods_id = $_GET['goods_id'];

        $res = [
            'status'=>0
        ];
        $spec = goodsModel::get_goods_specification( $goods_id );
        $res['spec_object'] = goodsModel::get_goods_spec_obj( $goods_id );

        $specification = [];
        foreach( $spec as $item ){
            $specification[ $item['name'] ]['name'] = $item['name'];
            $specification[ $item['name'] ]['values'][] = [
                'name'=>$item['value']
            ];
        }

        $res['specification'] = $specification;

        return json( $res );

    }
    
    /**
     * 商品上架
     * @return \think\response\Json
     */
    public function onSale(){
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '上架成功'
        ];
        
        try {
            $result = GoodsModel::updateStatus( $ids, 1 );
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '上架失败：' . $e->getMessage();
        }
        
        return json( $res );
    }
    
    /**
     * 商品下架
     * @return \think\response\Json
     */
    public function offSale(){
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '下架成功'
        ];
        
        try {
            $result = GoodsModel::updateStatus( $ids, 0 );
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '下架失败：' . $e->getMessage();
        }
        
        return json( $res );
    }

}